<template>
  <div class="home-page">
    <!-- 搜索区域 -->
    <section class="search-section">
      <div class="search-box">
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="从海量图片中搜索..."
          size="large"
          enter-button
          @search="loadPictures"
        />
      </div>
    </section>

    <!-- 分类 -->
    <section class="filter-section">
      <div class="filter-title">分类：</div>
      <a-radio-group v-model:value="selectedCategory" button-style="solid" @change="loadPictures">
        <a-radio-button value="">全部</a-radio-button>
        <a-radio-button v-for="c in categories" :key="c" :value="c">{{ c }}</a-radio-button>
      </a-radio-group>
    </section>

    <!-- 标签 -->
    <section class="filter-section">
      <div class="filter-title">标签：</div>
      <a-space wrap>
        <a-checkable-tag
          v-for="tag in popularTags"
          :key="tag"
          :checked="selectedTags.includes(tag)"
          @change="(checked) => handleTagToggle(tag, checked)"
        >
          {{ tag }}
        </a-checkable-tag>
      </a-space>
    </section>

    <!-- 图片网格 -->
    <section class="picture-section">
      <a-spin :spinning="pictureLoading">
        <div v-if="featuredPictures.length === 0" class="empty-tip">暂无图片</div>
        <div class="picture-grid">
          <div
            v-for="pic in featuredPictures"
            :key="pic.id"
            class="picture-card"
            @click="handlePictureClick(pic)"
          >
            <div class="picture-img-wrapper">
              <img :src="pic.url" :alt="pic.name" />
            </div>
            <div class="picture-info">{{ pic.name }}</div>
          </div>
        </div>

        <!-- 添加分页控件 -->
        <div style="text-align: center; margin-top: 20px">
          <a-pagination
            v-model:current="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            show-size-changer
            :page-size-options="pageSizeOptions"
            @change="handlePageChange"
            @show-size-change="handlePageSizeChange"
          />
        </div>
      </a-spin>
    </section>

    <!-- 详情弹窗 -->
    <a-modal
      v-model:open="pictureModalVisible"
      :title="selectedPicture?.name || '图片详情'"
      :footer="null"
      width="800px"
      wrapClassName="picture-detail-modal"
    >
      <div class="picture-detail-container" v-if="selectedPicture">
        <!-- 图片展示区域 -->
        <div class="picture-preview">
          <img :src="selectedPicture.url" :alt="selectedPicture.name" class="preview-image" />
          <div class="zoom-icon" @click="showLargeImage">
            <EyeOutlined />
          </div>
        </div>

        <!-- 信息展示区域 -->
        <div class="picture-info-section">
          <a-descriptions :column="1" size="small">
            <a-descriptions-item label="图片名称">{{ selectedPicture.name }}</a-descriptions-item>
            <a-descriptions-item label="简介">{{
              selectedPicture.introduction || '-'
            }}</a-descriptions-item>
            <a-descriptions-item label="分类">{{
              selectedPicture.category || '-'
            }}</a-descriptions-item>
            <a-descriptions-item label="标签">
              <a-tag v-for="t in selectedPicture.tags" :key="t">{{ t }}</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="尺寸">
              {{ selectedPicture.picWidth }} × {{ selectedPicture.picHeight }}
            </a-descriptions-item>
            <a-descriptions-item label="大小">
              {{ (selectedPicture.picSize / 1024).toFixed(2) }} KB
            </a-descriptions-item>
            <a-descriptions-item label="格式">{{ selectedPicture.picFormat }}</a-descriptions-item>
            <a-descriptions-item label="比例">{{
              selectedPicture.picScale.toFixed(2)
            }}</a-descriptions-item>
            <a-descriptions-item label="创建时间">{{ selectedPicture.createTime }}</a-descriptions-item>
          </a-descriptions>

          <div class="action-buttons">
            <a-button type="primary" @click="handleDownloadPicture">下载图片</a-button>
            <a-button>收藏</a-button>
          </div>
        </div>
      </div>
    </a-modal>

    <!-- 大图查看器 -->
    <a-image
      v-model:visible="largeImageVisible"
      :src="selectedPicture?.url"
      :preview="{
        visible: largeImageVisible,
        onVisibleChange: (visible: boolean) => { largeImageVisible = visible },
        src: selectedPicture?.url,
      }"
      style="display: none"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  EyeOutlined
} from '@ant-design/icons-vue'
import {
  downloadPictureUsingPost,
  listPictureVoByPageWithCacheUsingPost
} from '@/api/pictureController.ts'
import { listCategoryUsingPost } from '@/api/pictureCategoryController.ts'
import { listTagUsingPost } from '@/api/pictureTagController.ts'
import { downloadImage } from '@/utils/index.ts'

const searchKeyword = ref('')
const categories = ref<string[]>([])
const popularTags = ref<string[]>([])
const selectedCategory = ref('')
const selectedTags = ref<string[]>([])
const featuredPictures = ref<API.PictureVO[]>([])
const pictureLoading = ref(false)
const pictureModalVisible = ref(false)
const largeImageVisible = ref(false)
const selectedPicture = ref<API.PictureVO | null>(null)

const loadMeta = async () => {
  // 获取所有分类
  const categoryRes = await listCategoryUsingPost({})
  if (categoryRes.data.code === 0) {
    categories.value = categoryRes.data.data?.map((item: any) => item.categoryName) || []
  }

  // 获取所有标签
  const tagRes = await listTagUsingPost({})
  if (tagRes.data.code === 0) {
    popularTags.value = tagRes.data.data?.map((item: any) => item.tagName) || []
  }
}

// 新增分页相关响应式变量
const currentPage = ref(1)
const pageSize = ref()
const pageSizeOptions = ref(['5', '10', '15', '20'])
const total = ref(0)
const loadPictures = async () => {
  pictureLoading.value = true
  try {
    const res = await listPictureVoByPageWithCacheUsingPost({
      searchText: searchKeyword.value,
      category: selectedCategory.value,
      tags: selectedTags.value,
      pageSize: pageSize.value,
      current: currentPage.value,
    })

    // 更新总数和当前页数据
    featuredPictures.value = res.data.data.records || []
    total.value = res.data.data.total || 0
  } catch {
    message.error('加载图片失败')
  } finally {
    pictureLoading.value = false
  }
}
// 处理页码变化事件
const handlePageChange = (page: number) => {
  currentPage.value = page
  loadPictures()
}

// 处理页面大小变化事件
const handlePageSizeChange = (current: number, size: number) => {
  pageSize.value = size
  currentPage.value = 1 // 重置到第一页
  loadPictures()
}

// 处理标签切换事件
const handleTagToggle = (tag: string, checked: boolean) => {
  if (checked) selectedTags.value.push(tag)
  else selectedTags.value = selectedTags.value.filter((t) => t !== tag)
  loadPictures()
}
// 处理图片点击事件
const handlePictureClick = (pic: API.PictureVO) => {
  selectedPicture.value = pic
  pictureModalVisible.value = true
}

// 显示大图
const showLargeImage = () => {
  largeImageVisible.value = true
}

// 添加下载图片处理函数
const handleDownloadPicture = async () => {
  if (!selectedPicture.value?.id) {
    message.error('无效的图片ID')
    return
  }
  try {
    // 调用后端接口获取 OSS 下载地址
    const res = await downloadPictureUsingPost({
      id: selectedPicture.value.id.toString()
    })

    if (res.data.code === 0) {
      // 假设返回的数据中包含 downloadUrl 字段
      console.log(res.data.data)
      const downloadUrl = res.data.data
      // 处理下载
      downloadImage(downloadUrl)
      message.success('图片已下载')
    }
    else {
      message.error('下载图片失败')
    }
  } catch (error) {
    message.error('下载图片失败')
  }
}


onMounted(() => {
  loadMeta()
  loadPictures()
})
</script>

<style scoped>
.home-page {
  background: #fff;
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.search-section {
  text-align: center;
  margin-bottom: 24px;
}

.search-box {
  max-width: 600px;
  margin: 0 auto;
}

.filter-section {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-title {
  font-weight: 500;
  margin-right: 8px;
}

.picture-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.picture-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: transform 0.2s;
  background: #fafafa;
}

.picture-card:hover {
  transform: translateY(-4px);
}

.picture-img-wrapper {
  width: 100%;
  padding-bottom: 100%; /* 1:1 正方形容器 */
  position: relative;
  background: #f0f0f0;
}

.picture-img-wrapper img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.picture-info {
  padding: 8px;
  font-weight: 500;
  text-align: center;
  background: #fff;
}

.empty-tip {
  text-align: center;
  color: #999;
  padding: 40px;
}

/* 图片详情弹窗样式 */
.picture-detail-container {
  display: flex;
  gap: 24px;
  max-height: 60vh;
  overflow-y: auto;
}

.picture-preview {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 8px;
  min-width: 0;
  position: relative;
}

.preview-image {
  max-width: 100%;
  max-height: 50vh;
  object-fit: contain;
  border-radius: 4px;
}

.zoom-icon {
  position: absolute;
  bottom: 12px;
  right: 12px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.3s;
}

.zoom-icon:hover {
  background: rgba(0, 0, 0, 0.8);
}

.picture-info-section {
  flex: 1;
  min-width: 0;
}

.action-buttons {
  margin-top: 20px;
  text-align: right;
}

/* 在移动端调整布局 */
@media (max-width: 768px) {
  .picture-detail-container {
    flex-direction: column;
  }

  .picture-preview {
    max-height: 300px;
  }
}
</style>
